package artid.com.arttogo.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import java.util.Map;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.AppItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.db.DataKeeper;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.Constant;

/**
 * 账户管理
 * 绑定qq、微信
 *
 */
public class AccountMangActivity extends BaseActivity implements OnClickListener {
	private RelativeLayout mUser,mWx,mQQ;
	private TextView mTextUser,mTextQQ,mTextWx;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account_mang);
		ArtToGoApp.getInstance().addActivity(AccountMangActivity.this);
		initView();
	}
 
	private void initView() {
		mContext = this;
		mBack = (ImageView) findViewById(R.id.back_btn);
		mBack.setVisibility(View.VISIBLE);
		mBack.setOnClickListener(this);
		mTittle = (TextView) findViewById(R.id.tittle_text);
		mTittle.setText("账号管理");
//		mUser = (View)findViewById(R.id.set_rela_user);
		mTextUser = (TextView)findViewById(R.id.set_text_phone);
		//显示手机号码，隐藏中间几位
		String mobile = AppUtil.getUser().getMobile();
		String mobilePrefix = mobile.substring(0,3);
		String mobileAppend = mobile.substring(7,11);
		mTextUser.setText(mobilePrefix+"****"+mobileAppend);
		mTextQQ = (TextView)findViewById(R.id.set_text_qq);
		if (AppUtil.getUser().getIsQQ()) {
			mTextQQ.setText("已绑定");
		}else {
			mTextQQ.setText("未绑定");
			mTextQQ.setTextColor(Color.BLACK);
		}
		mTextWx = (TextView)findViewById(R.id.set_text_wx);
		if (AppUtil.getUser().getIsWx()) {
			mTextWx.setText("已绑定");
		}else {
			mTextWx.setText("未绑定");
			mTextWx.setTextColor(Color.BLACK);
		}
		mWx = (RelativeLayout)findViewById(R.id.set_rela_wx);
		mWx.setOnClickListener(this);
		mQQ = (RelativeLayout)findViewById(R.id.set_rela_qq);
		mQQ.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.set_rela_wx:
			if (AppUtil.getUser().getIsWx()) {
				AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle("提示").setMessage("是否解除绑定？")
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								clearqq("1");
							}
						}).setNegativeButton("取消", null).show();
			}else {
				UMWXHandler wxhHandler = new UMWXHandler(mContext,
						Constant.WX_APP_ID, Constant.WX_APP_KEY);
				wxhHandler.addToSocialSDK();
				wxlogin(SHARE_MEDIA.WEIXIN);
			}
			
			break;
		
		case R.id.set_rela_qq:
			if (AppUtil.getUser().getIsQQ()) {
				AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle("提示").setMessage("是否解除绑定？")
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								clearqq("0");
							}
						}).setNegativeButton("取消", null).show();
			}else {
				
				UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(
						AccountMangActivity.this, Constant.TENCENT_APP_KEY,
						Constant.TENCENT_APP_SECRET);
				qqSsoHandler.addToSocialSDK();
				wxlogin(SHARE_MEDIA.QQ);
			}
			break; 
			
		case R.id.back_btn:
			finish();
			break;
		default:
			break;
		}
		
	}

	/**
	 * 绑定qq，请求接口
	 * @param qqtoken
	 * @param type
	 */
	void bdqq(String qqtoken, final String type){
		VolleyBasic.getInstance(AccountMangActivity.this).post(Cache.blindqq,
				VolleyMap.getInstance().blindqq(qqtoken,type), AppItem.class, new VolleyCallback() {
					
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						if (type.equals("0")) {
							AppUtil.getUser().setIsQQ(true);
							mTextQQ.setText("已绑定");
							mTextQQ.setTextColor(Color.GRAY);
						}else {
							AppUtil.getUser().setIsWx(true);
							
							mTextWx.setText("已绑定");
							mTextWx.setTextColor(Color.GRAY);
						}
						DataKeeper.keepSerializable(mContext, AppUtil.getUser());
					}
					
					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						
					}
				});
	}
	
	void clearqq(final String type){
		VolleyBasic.getInstance(AccountMangActivity.this).post(Cache.clearqq,
				VolleyMap.getInstance().clearqq(type), AppItem.class, new VolleyCallback() {
					
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						if (type.equals("0")) {
							AppUtil.getUser().setIsQQ(false);
							mTextQQ.setText("未绑定");
							mTextQQ.setTextColor(Color.BLACK);
						}else {
							AppUtil.getUser().setIsWx(false);
							mTextWx.setText("未绑定");
							mTextWx.setTextColor(Color.BLACK);
						}
						DataKeeper.keepSerializable(mContext, AppUtil.getUser());
					}
					
					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						
					}
				});
	}
	private UMSocialService mController = UMServiceFactory
			.getUMSocialService("com.umeng.share");

	private void wxlogin(final SHARE_MEDIA platform) {
		mController.doOauthVerify(mContext, platform,
				new UMAuthListener() {

					@Override
					public void onStart(SHARE_MEDIA platform) {
						
					}

					@Override
					public void onError(SocializeException e,
							SHARE_MEDIA platform) {
					}

					@Override
					public void onComplete(Bundle value, SHARE_MEDIA platform) {
						String uid = value.getString("uid");
						if (!TextUtils.isEmpty(uid)) {
							getUserInfo(platform);
						} else {
							Toast.makeText(mContext, "授权失败...",
									Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onCancel(SHARE_MEDIA platform) {
					}
				});
	}
	/**
	 * 获取授权平台的用户信息
	 */
	private void getUserInfo(final SHARE_MEDIA platform) {
		mController.getPlatformInfo(mContext, platform,
				new UMDataListener() {

					@Override
					public void onStart() {

					}

					@Override
					public void onComplete(int status, Map<String, Object> info) {
						// String showText = "";
						// if (status == StatusCode.ST_CODE_SUCCESSED) {
						// showText = "用户名：" +
						// info.get("screen_name").toString();
						// Log.d("#########", "##########" + info.toString());
						// } else {
						// showText = "获取用户信息失败";
						// }
						if (info != null) {
							Log.d("第三方登录info", info.toString());
							//通过字符串截取获得绑定的token
							if (platform.equals(SHARE_MEDIA.QQ)) {
								String strQQtoken = (String) info.get("profile_image_url");
								strQQtoken = strQQtoken.substring(strQQtoken.indexOf("qqapp/")+7);
								strQQtoken = strQQtoken.substring(strQQtoken.indexOf("/")+1);
								strQQtoken = strQQtoken.substring(0,strQQtoken.indexOf("/"));
								bdqq(strQQtoken, "0");
								
//								Toast.makeText(LoginActivity.this, strQQtoken,
//										Toast.LENGTH_SHORT).show();
							}
							if (platform.equals(SHARE_MEDIA.WEIXIN)) {
								String strwxtoken = (String) info.get("unionid");
								bdqq(strwxtoken, "1");
//								Toast.makeText(LoginActivity.this, strwxtoken,
//										Toast.LENGTH_SHORT).show();
							}
							
							
						}
					}
				});
	}
}
